'''
Created on 10.03.2012

@author: myaut
'''

from salsa.util.io import IOFeederReply

from salsa.service import Service
from salsa.util import LoggerSeverity
from salsa.util.rpc import RPCError, RPCInfo, RPCProtocol

import shelve

class TypeDB(Service):
    def __init__(self):
        Service.__init__(self)
        
        self.typedb_path = self.core.abs_data_path(self.params.get('typedb_path', 'typedb.db'))
        self.typedb = shelve.open(self.typedb_path)
        
        self.logger.log(LoggerSeverity.LS_INFO, 'TypeDB connected to %s' % self.typedb_path)
    
    def add_type(self, name, coord, ref):
        self.logger.log(LoggerSeverity.LS_NOTICE, 'Added type %s' % name)
        
        if name in self.typedb:
            l = self.typedb[name]
            l.append((coord, ref))
            self.typedb[name] = l
        else:
            self.typedb[name] = [(ref, coord)]
        
        return RPCProtocol.STATUS_OK
    
    def list_types(self):
        return IOFeederReply(iter(self.typedb.items()))
    
    def type_exists(self, name):
        return name in self.typedb
    
    def type_info(self, name):
        try:
            info = self.typedb[name]
        except KeyError:
            raise RPCError(RPCError.BAD_REQUEST)
        
        return info
    
    def delete_type(self, name):
        del self.typedb[name]
        
        return RPCProtocol.STATUS_OK
    
    def do_stop(self):
        self.typedb.close()

TypeDB.rpc_info = RPCInfo()
TypeDB.rpc_info.register(TypeDB, 'add_type', 'type_exists', 'type_info', 
                         'list_types', 'delete_type')